package com.bonc.modules.rpt.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bonc.datasource.annotation.DataSource;
import com.bonc.modules.rpt.dao.ArcInfoAudioDao;
import com.bonc.modules.rpt.dao.ArcInfoAudioDealTimeDao;
import com.bonc.modules.rpt.entity.ArcInfoAudio;
import com.bonc.modules.rpt.entity.ArcInfoAudioDealTime;
import com.bonc.modules.rpt.service.ArcInfoAudioService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@DataSource("data")
@Service
public class ArcInfoAudioServiceImpl extends ServiceImpl<ArcInfoAudioDao, ArcInfoAudio> implements ArcInfoAudioService {

    @Autowired
    private ArcInfoAudioDao arcInfoAudioDao;

    @Autowired
    private ArcInfoAudioDealTimeDao arcInfoAudioDealTimeDao;

    @Autowired
    @Qualifier("data")
    private javax.sql.DataSource dataSource;

    @Override
    public void saveArcInfoAudioList(List<ArcInfoAudio> arcInfoAudioList){

        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        boolean flag = TransactionSynchronizationManager.isSynchronizationActive();
        if(!flag) {
            TransactionSynchronizationManager.initSynchronization();
        }
        javax.sql.DataSource dataSource = jdbcTemplate.getDataSource();
        Connection conn = DataSourceUtils.getConnection(dataSource);
        Boolean ac = null;
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

        try {
            ac = conn.getAutoCommit();
            conn.setAutoCommit(false);

            String insertSql = "INSERT INTO TB_MID_SERV_ARC_INFO_AUDIO (CASE_NO, AUDIO_PATH, MODIFY_TIME, CREATE_TIME) " +
                    "VALUES (?, ?, to_date(?, 'yyyymmddhh24miss'), sysdate)";
            List<Object[]> batchArgs=new ArrayList<Object[]>(1000);
            for(ArcInfoAudio arcInfoAudio : arcInfoAudioList){
                batchArgs.add(new Object[]{arcInfoAudio.getCaseNo(), arcInfoAudio.getAudioPath(), df.format(arcInfoAudio.getModifyTime())});
                if(batchArgs.size() == 1000){
                    jdbcTemplate.batchUpdate(insertSql, batchArgs);
                    batchArgs.clear();
                }
            }
            if(batchArgs.size() > 0){
                jdbcTemplate.batchUpdate(insertSql, batchArgs);
                batchArgs.clear();
            }

            ArcInfoAudio arcInfoAudio = arcInfoAudioList.stream().max((e1, e2) -> Long.compare(e1.getMTime(), e2.getMTime())).get();
            List<Map<String, Object>> list = jdbcTemplate.queryForList("select TIME_STAMP from TB_MID_SERV_ARC_INFO_AUDIO_DEAL_TIME");
            String sql;
            if(ObjectUtil.isEmpty(list)){
                sql = "INSERT INTO TB_MID_SERV_ARC_INFO_AUDIO_DEAL_TIME (TIME_STAMP) VALUES (?)";
            } else {
                sql = "UPDATE TB_MID_SERV_ARC_INFO_AUDIO_DEAL_TIME SET TIME_STAMP = ?";
            }
            jdbcTemplate.update(sql, arcInfoAudio.getMTime());
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            if(!flag) {
                TransactionSynchronizationManager.clearSynchronization();
            }
            if(ac != null){
                try {
                    conn.setAutoCommit(ac);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public List<ArcInfoAudio> queryData(String caseNo) {

        QueryWrapper<ArcInfoAudio> qw = new QueryWrapper<>();
        qw.select("distinct case_no, audio_path");
        LambdaQueryWrapper<ArcInfoAudio> queryWrapper = qw.lambda();

        if(ObjectUtil.isNotEmpty(caseNo)){
            queryWrapper.eq(ArcInfoAudio::getCaseNo, caseNo);
        }
        return arcInfoAudioDao.selectList(queryWrapper);
    }
}
